package com.weng.coder.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.weng.cloud.utils.CloudAuthUtil;
import com.weng.coder.common.utils.Constants;
import com.weng.coder.entity.Project;
import com.weng.coder.entity.ProjectUser;
import com.weng.coder.service.ProjectUserService;
import com.weng.framework.core.model.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.weng.coder.service.CodeTableService;
import com.weng.coder.service.NameRuleService;
import com.weng.coder.service.ProjectService;
import com.weng.coder.service.TemplateService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.util.WebUtils;

/**
 * 项目 Web API
 *
 * @作者 wengzhonghui
 * @创建时间 2018-02-24 10:16:58
 */
@RestController
@RequestMapping("/project") 
@Api(value = "项目相关接口")
@Slf4j
public class ProjectController{
	@Resource
	private ProjectService projectService;
	@Resource
	private CodeTableService codeTableService;
	@Resource
	private TemplateService templateService;
	@Resource
	private NameRuleService nameRuleService;
	@Resource
	private ProjectUserService projectUserService;
	

	 /**
	 * 获取分页数据
	 */
	 @ResponseBody
	 @RequestMapping(value="/list",method=RequestMethod.POST)
	 @ApiOperation(value = "分页获取项目列表", notes = "分页获取项目列表")
	 @ApiImplicitParams({
        @ApiImplicitParam(paramType = "query",name = "pageNo",dataType ="Integer" ,required = true,value = "页数"),
        @ApiImplicitParam(paramType = "query",name = "pageSize",dataType ="Integer" ,required = true,value = "每页数量")
	 })
	 public ResponseData getDataByPage(String name, Boolean isBuildIn,Integer pageNo, Integer pageSize
			 , HttpServletRequest request)throws Exception{
		 
		 String userId = CloudAuthUtil.getCurUserId(request);
		 List<Project> projectList = this.projectService.getProjectListByUser(name, isBuildIn, userId);
		 return ResponseData.success(projectList);
	 }
	
	 /**
	 * 获取项目
	 * 
	 */
	@RequestMapping(value="get-one",method=RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "获取项目", notes = "获取项目")
	public ResponseData getProject(String id, Model model
			,HttpServletRequest request) throws Exception{
		if(StringUtils.isEmpty(id)){
			return ResponseData.failed("项目Id不能为空！");
		}
		
		Project project = this.projectService.getOne(id);
		return ResponseData.success(project);
	}
	 
	/**
	 * 添加项目
	 * 
	 */
	@RequestMapping(value="add",method=RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "添加项目", notes = "添加项目")
	@Transactional
	public ResponseData addProject(Project project, Model model
			,HttpServletRequest request) throws Exception{
		if(project==null ){
			return ResponseData.failed("项目不能为空！");
		}
		project.setId(null);
		String userId = CloudAuthUtil.getCurUserId(request);
		
		project.setIsBuildIn(Constants.IS_BUILD_IN_FALSE);
		project = projectService.save(project);
		ProjectUser projectUser = new ProjectUser(project.getId(),userId, Constants.IS_OWNER_TRUE);
		projectUserService.save(projectUser);
		
		request.setAttribute(Constants.AOP_LOG_DESCRIPTION, "添加项目，【"+project.getName()+"】");
		return ResponseData.success("添加项目成功！");
	}
	
	/**
	 * 更新项目
	 */
	@RequestMapping(value="update",method=RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "更新项目", notes = "更新项目")
	public ResponseData updateProject(Project project,HttpServletRequest request) throws Exception{
		if(project==null ){
			return ResponseData.failed("项目不能为空！");
		}
		Project oldProject = this.projectService.getOne(project.getId());
		if(oldProject == null){
			return ResponseData.failed("项目不存在，无法更新！");
		}
		if(oldProject.getIsBuildIn()!=null &&  Constants.IS_BUILD_IN_TRUE.compareTo(oldProject.getIsBuildIn())==0){
			return ResponseData.failed("更新失败，该项目是示例模板项目，不允许修改，请在个人项目中修改！");
		}
		project.setIsBuildIn(oldProject.getIsBuildIn());
		projectService.save(project);
		request.setAttribute(Constants.AOP_LOG_DESCRIPTION, "更新项目，账号【"+project.getId()+"】");
		return ResponseData.success("更新成功！");
	}
	
	
	/**
	 * 删除项目
	 */
	@RequestMapping(value="delete",method=RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "删除项目,只支持删除一个项目", notes = "删除项目,只支持删除一个项目")
	@Transactional
	public  ResponseData deleteProject( String ids
			,HttpServletRequest request) {
		String[] projectIdList = ids.split(",");
		if(projectIdList == null || projectIdList.length < 1){
			return ResponseData.failed("项目ID不能为空");
		}
		String userId = CloudAuthUtil.getCurUserId(request);
		String projectId = projectIdList[0];
		ResponseData oprationResult = this.projectService.deleteProjectOfRelate(projectId, userId);
		return oprationResult;
	}

	/**
	 * 同步数据库
	 * 
	 * @author wengzhonghui 2017年7月12日
	 * @param request
	 * @param response
	 * @return
	 */
	@ApiOperation(value = "同步数据库", notes = "同步数据库")
	@RequestMapping(value = "/synchronize", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData synchronize(String projectId, HttpServletRequest request, HttpServletResponse response) {
		boolean result = false;
		try {
			Project project = this.projectService.getOne(projectId);
			if(project == null){
				return ResponseData.failed("很遗憾，同步失败！项目不存在!");
			}
			if(StringUtils.isEmpty(project.getDbUrl()) || StringUtils.isEmpty(project.getDbName())){
				return ResponseData.failed("很遗憾，同步失败！请检查项目是否配置项目URL地址和数据库名称!");
			}
			result = this.projectService.synchronize(project);
		} catch (Exception e) {
			log.error("同步表失败，项目id为：" + projectId, e);
			return ResponseData.failed("很遗憾，同步失败！请检查数据库连接信息是否正确!");
		}
		return result ? ResponseData.success("恭喜您，同步成功！"):
			ResponseData.failed("很遗憾，同步失败！请查看系统日志或联系管理员。");
	}
	
	/**
	 * 复制项目
	 * 
	 * @author wengzhonghui 2017年7月12日
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/copy-project", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData copyProject(String projectId, HttpServletRequest request, HttpServletResponse response) {
		String userId = CloudAuthUtil.getCurUserId(request);
		boolean isSuccess = this.projectService.copyProject(projectId, userId);
		if(isSuccess){
			return ResponseData.success("复制成功!");
		}else{
			return ResponseData.failed("复制失败");
		}
	}

}

